package com.ruoyi.web.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAppRedPacketGetService;
import com.ruoyi.system.service.IAppRedPacketSendService;
import com.ruoyi.system.service.IAppTradeRecordService;
import com.ruoyi.system.service.IAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("app/redPacket")
@Api("红包接口")
public class ForAppRedPacketController extends BaseController {

    @Autowired
    private IAppUserService userService;
    @Autowired
    private IAppRedPacketSendService redPacketSendService;
    @Autowired
    private IAppRedPacketGetService redPacketGetService;
    @Autowired
    private IAppTradeRecordService tradeRecordService;

    @PostMapping("sendRedPacket")
    @ApiOperation("发送红包")
    public AjaxResult sendRedPacket(@ApiParam("类型，0：一对一红包，1：群红包") @RequestParam Integer type,
                                    @ApiParam("群红包类型，0：普通红包，1：拼手气红包，2、口令红包") Integer groupType,
                                    @ApiParam("发送总金额") @RequestParam BigDecimal sendTotal,
                                    @ApiParam("祝福语") @RequestParam String greeting,
                                    @ApiParam("红包个数") @RequestParam Integer shareNum,
                                    @ApiParam("红包口令") String command,
                                    @ApiParam("群id") String groupId) {
        return sendShareMethod(getUserId(), type, groupType, sendTotal, greeting, shareNum, command, groupId);
    }

    @PostMapping("v1/sendRedPacket")
    @ApiOperation("Version1：发送红包")
    public AjaxResult sendRedPacketInVersion1(@ApiParam("类型，0：一对一红包，1：群红包") @RequestParam Integer type,
                                              @ApiParam("群红包类型，0：普通红包，1：拼手气红包，2、口令红包") Integer groupType,
                                              @ApiParam("发送总金额") @RequestParam BigDecimal sendTotal,
                                              @ApiParam("祝福语") @RequestParam String greeting,
                                              @ApiParam("红包个数") @RequestParam Integer shareNum,
                                              @ApiParam("红包口令") String command,
                                              @ApiParam("群id") String groupId,
                                              @ApiParam("支付密码") @RequestParam String payPass) {
        AppUser sendUser = userService.getById(getUserId());
        if (!payPass.equals(sendUser.getPayPass())) {
            return AjaxResult.error(-1, "用户支付密码错误！");
        }
        return sendShareMethod(getUserId(), type, groupType, sendTotal, greeting, shareNum, command, groupId);
    }

    /**
     * 发送红包共用method
     *
     * @param userId
     * @param type
     * @param groupType
     * @param sendTotal
     * @param greeting
     * @param shareNum
     * @param command
     * @param groupId
     * @return
     */
    public AjaxResult sendShareMethod(Long userId, Integer type, Integer groupType, BigDecimal sendTotal, String greeting,
                                      Integer shareNum, String command, String groupId) {
        BigDecimal minMoney = BigDecimal.valueOf(0.01).multiply(BigDecimal.valueOf(shareNum.longValue())).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (sendTotal.compareTo(minMoney) < 0) {
            return AjaxResult.error(-1, "红包发送不能小于最低金额：" + minMoney);
        }
        if (sendTotal.compareTo(BigDecimal.valueOf(200.00)) > 0) {
            return AjaxResult.error(-1, "红包发送金额最高200");
        }
        if (type == 1 && groupType == 0) {
            BigDecimal[] remainderArr = sendTotal.divideAndRemainder(minMoney);
            if (remainderArr[1].compareTo(BigDecimal.ZERO) > 0) {
                return AjaxResult.error(-1, "这个普通红包金额不能平分");
            }
        }
        if (type == 1 && groupType == 2 && StringUtils.isBlank(command)) {
            return AjaxResult.error(-1, "口令红包的口令不能为空");
        }
        if (type == 1 && groupType == 2 && groupId == null) {
            return AjaxResult.error(-1, "口令红包的群ID不能为空");
        }

        AppRedPacketSend redPacketSend = new AppRedPacketSend();
        redPacketSend.setCreateTime(new Date());
        redPacketSend.setUserId(userId);
        redPacketSend.setType(type);
        if (type == 1)
            redPacketSend.setGroupType(groupType);
        redPacketSend.setMoney(sendTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
        redPacketSend.setGreeting(greeting);
        redPacketSend.setShareNum(shareNum);
        redPacketSend.setStock(shareNum);
        redPacketSend.setRemainMoney(sendTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
        if (type == 1 && groupType == 2) {
            redPacketSend.setCommand(CommonUtils.encodeNickname(command));
            redPacketSend.setGroupId(groupId);
        }

        // 添加流水记录
        AppTradeRecord tradeRecord = new AppTradeRecord();
        tradeRecord.setCreateTime(new Date());
        tradeRecord.setUserId(userId);
        tradeRecord.setType(2);
        tradeRecord.setMoney(sendTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
        tradeRecord.setAuditType(2);
        tradeRecordService.insertAppTradeRecord(tradeRecord);
        return redPacketSendService.sendRedPacket(redPacketSend);
    }

    @PostMapping("getPacketInfo")
    @ApiOperation("获取发送红包信息")
    public AjaxResult getPacketInfo(@ApiParam("红包id") @RequestParam Long redPacketId) {
        AppRedPacketSend redPacketSendEntity = redPacketSendService.getById(redPacketId);
        AppUser sendUser = userService.getById(redPacketSendEntity.getUserId());
        redPacketSendEntity.setUserName(sendUser.getUsername());
        redPacketSendEntity.setHeadImg(sendUser.getHeadImg());
        redPacketSendEntity.setMoney(redPacketSendEntity.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
        redPacketSendEntity.setRemainMoney(redPacketSendEntity.getRemainMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
        if (redPacketSendEntity.getType() == 1 && redPacketSendEntity.getGroupType() == 2)
            redPacketSendEntity.setCommand(redPacketSendEntity.getCommand());

        boolean hasGet = false;
        if (getUserId().equals(redPacketSendEntity.getUserId()) && redPacketSendEntity.getType() == 0) {
            hasGet = true;
        }
        QueryWrapper<AppRedPacketGet> getQw = new QueryWrapper<>();
        getQw.eq("user_id", getUserId());
        getQw.eq("packet_id", redPacketId);
        long count = redPacketGetService.count(getQw);
        if (count > 0) {
            hasGet = true;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("redPacketSendEntity", redPacketSendEntity);
        map.put("hasGet", hasGet);
        return AjaxResult.ok(0, "获取成功", map);
    }

    @PostMapping("receiveRedPacket")
    @ApiOperation("领取红包")
    public AjaxResult receiveRedPacket(@ApiParam("红包id") @RequestParam Long redPacketId) {
        AppRedPacketSend redPacketSendEntity = redPacketSendService.getById(redPacketId);
        if (redPacketSendEntity.getStatus() > 0) {
            return AjaxResult.error(-9, "红包已领完");
        }
        if (redPacketSendEntity.getType() == 0) {
            if (getUserId() == redPacketSendEntity.getUserId()) {
                Map<String, Object> map = new HashMap<>();
                map.put("redPacketSend", redPacketSendEntity);
                return AjaxResult.ok(0, "获取成功", map);
            }
            return redPacketGetService.getSingleRedPacket(getUserId(), redPacketSendEntity);
        } else {
            return redPacketGetService.getGroupRedPacket(getUserId(), redPacketSendEntity);
        }
    }

    @PostMapping("receiveByCommand")
    @ApiOperation("凭口令领取红包")
    public AjaxResult filterRedPacketInGroupByCommand(@ApiIgnore @RequestAttribute("userId") Long userId,
                                                      @ApiParam("群id") @RequestParam Long groupId,
                                                      @ApiParam("红包口令") @RequestParam String redCommand) {
        /**
         * 获取群内待领取的口令红包
         */
        QueryWrapper<AppRedPacketSend> sendWrapper = new QueryWrapper<>();
        sendWrapper.eq("group_id", groupId);
        sendWrapper.eq("type", 1);
        sendWrapper.eq("group_type", 2);
        sendWrapper.eq("status", 0);
        sendWrapper.eq("command", CommonUtils.encodeNickname(redCommand));
        sendWrapper.orderByDesc("create_time");
        List<AppRedPacketSend> sendList = redPacketSendService.list(sendWrapper);
        if (sendList.size() == 0) {
            return AjaxResult.error(-9, "红包已领完");
        }

        AppRedPacketSend redPacketSendEntity = sendList.get(0);
        if (redPacketSendEntity.getStatus() > 0) {
            return AjaxResult.error(-9, "红包已领完");
        }
        return redPacketGetService.getGroupRedPacket(userId, redPacketSendEntity);
    }

    @PostMapping("getReceiveRedList")
    @ApiOperation("查看已领取完红包手气")
    public AjaxResult getReceiveRedList(@ApiParam("红包id") @RequestParam Long redPacketId) {
        return redPacketGetService.getSendRedInfoAndGetList(getUserId(), redPacketId);
    }

    @PostMapping("getUserRedList")
    @ApiOperation("获取用户红包记录")
    public AjaxResult getUserRedList(@ApiParam("页数") @RequestParam(defaultValue = "1") int page,
                                     @ApiParam("条数") @RequestParam(defaultValue = "10") int limit) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("page", page);
        params.put("limit", limit);

        QueryWrapper<AppRedPacketGet> qw = new QueryWrapper<>();
        qw.eq("user_id", getUserId());
        qw.orderByDesc("create_time");
        Page<AppRedPacketGet> pageObj = redPacketGetService.page(new Page<>(page, limit), qw);

        AppUser getUser = userService.getById(getUserId());
        for (int i = 0; i < pageObj.getRecords().size(); i++) {
            AppRedPacketGet getEntity = (AppRedPacketGet) pageObj.getRecords().get(i);
            getEntity.setUserName(getUser.getUsername());
            getEntity.setHeadImg(getUser.getHeadImg());
            getEntity.setMoney(getEntity.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalPage", pageObj.getTotal());
        jsonObject.put("pageSize", pageObj.getPages());
        jsonObject.put("redTotalReceive", getUser.getRedTotalReceive().setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("totalReceiveCount", redPacketGetService.count(qw));
        long totalBetterCount = redPacketGetService.count(
                new QueryWrapper<AppRedPacketGet>().eq("status", 1).eq("user_id", getUserId()));
        jsonObject.put("totalBetterCount", totalBetterCount);
        Map<String, Object> map = new HashMap<>();
        map.put("getRedList", pageObj.getRecords());
        map.put("info", jsonObject);
        return AjaxResult.ok(0, "获取成功", map);
    }

}
